﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.IO;
using System.Text;
using Microsoft.Phone.Net.NetworkInformation;
using System.Text.RegularExpressions;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Tasks;

namespace NearChat
{
    public partial class ModificaProfilo : PhoneApplicationPage
    {
        //storage dell'applicazione
        private static IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;

        //chooser delle pictures
        PhotoChooserTask photoChooser;

        private string user = "";
        private string index = "";
        private string image = "";
        private string frase = "";

        public ModificaProfilo()
        {
            InitializeComponent();

            //implementazione futura
            buttonBrowse.IsEnabled = false;
            buttonBrowse.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            //salvo l'utente
            user = appSettings["user"].ToString();
            index = appSettings["ID"].ToString();

            //carico i vecchi dati
            NameText.Text = user;
            FraseBox.Text = appSettings["frase"].ToString();

            image = appSettings["image"].ToString(); ; //l'URL della mia immagine
            BitmapImage urlProfilo = new BitmapImage(new Uri(image, UriKind.Absolute));
            ImageBrush sfondo = new ImageBrush();
            ImageSource src = urlProfilo;
            sfondo.ImageSource = src;
            imageProfilo.Background = sfondo;
        }

        private void buttonSalva_Tap(object sender, GestureEventArgs e)
        {
            bool isCorrect = true;

            //prelevo i dati
            frase = FraseBox.Text.ToString();
            image = URLbox.Text.ToString();

            //controllo url imagine
            Regex RgxUrl = new Regex("(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)?/{0,2}[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?");
            if (RgxUrl.IsMatch(image) == false)
                isCorrect = false;

            //carico la nuova immagine
            BitmapImage urlProfilo = new BitmapImage(new Uri(image, UriKind.Absolute));
            ImageBrush sfondo = new ImageBrush();
            ImageSource src = urlProfilo;
            sfondo.ImageSource = src;
            imageProfilo.Background = sfondo;

            //controllo frase
            frase = frase.Replace('|', '/');
            frase = frase.Replace('§', 'ç');

            if (isCorrect)
            {
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    //faccio request PHP al DB con gi aggiornamenti
                    Uri myDBuri = new Uri("http://www.nearchat.altervista.org/updateProfile.php");
                    HttpWebRequest profileRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                    profileRequest.Method = "POST";
                    profileRequest.ContentType = "application/x-www-form-urlencoded";
                    profileRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), profileRequest);
                }
                else
                    MessageBox.Show("connection error, please retry later.");

            }
            else
            {
                MessageBox.Show("errore inserimento campi");
            }
        }

        private void FraseBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            //FraseBox.Text = "";
        }

        void GetRequestStreamCallback(IAsyncResult callbackResult)
        {
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);

            // Create the post data
            string postData = "apikey=4nn!eSupp0rt&ID=" + index +"&image=" + image + "&frase=" + frase;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
        }//GetRequestStreamCallback

        void GetResponsetStreamCallback(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingUpdateProfilo(result));
            }
        }//GetResponsetStreamCallback

        void ParsingUpdateProfilo(string result)
        {
            string[] ris = majorSplit(result);
            ris = minorSplit(ris[0]);//sono sicuro che rappresenta un solo record

            if (ris[0] == "ERRORE")
            {
                MessageBox.Show(ris[1]);
            }
            else
            {
                appSettings["frase"] = frase;
                appSettings["image"] = image;

                //NavigationService.RemoveBackEntry();
                NavigationService.GoBack();
            }
        }//ParsingUpdateProfilo

        //splitta la stringa passata in base a |
        private string[] minorSplit(string result)
        {
            return result.Split('|');
        }

        //splitta la stringa passata in base a §
        private string[] majorSplit(string result)
        {
            return result.Split('§');
        }
        /*
        private void buttonBrowse_Click(object sender, RoutedEventArgs e)
        {
            photoChooser = new PhotoChooserTask();
            photoChooser.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);
            photoChooser.Show();
        }
        
        void photoChooserTask_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                //a video l'immagine
                BitmapImage urlProfilo = new BitmapImage();
                urlProfilo.SetSource(e.ChosenPhoto);
                imgProfiloUtente.Source = urlProfilo;

                const int BLOCK_SIZE = 4096;

                Uri uri = new Uri("http://nearchat.altervista.org/profile", UriKind.Absolute);

                WebClient wc = new WebClient();
                wc.AllowReadStreamBuffering = true;
                wc.AllowWriteStreamBuffering = true;
                wc.Credentials = new NetworkCredential("nearchat", "sobsubepvi75");

                // what to do when write stream is open
                wc.OpenWriteCompleted += (s, args) =>
                {
                    using (BinaryReader br = new BinaryReader(e.ChosenPhoto))
                    {
                        using (BinaryWriter bw = new BinaryWriter(args.Result))
                        {
                            long bCount = 0;
                            long fileSize = e.ChosenPhoto.Length;
                            byte[] bytes = new byte[BLOCK_SIZE];
                            do
                            {
                                bytes = br.ReadBytes(BLOCK_SIZE);
                                bCount += bytes.Length;
                                bw.Write(bytes);
                            } while (bCount < fileSize);
                        }
                    }
                };

                // what to do when writing is complete
                wc.WriteStreamClosed += (s, args) =>
                {
                    MessageBox.Show("Send Complete");
                };

                // Write to the WebClient
                wc.OpenWriteAsync(uri, "POST");

            }
        }
        */
        private void URLbox_Tap(object sender, GestureEventArgs e)
        {
            URLbox.Text = "http://";
        }

    }

}